#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

void childw(int wfd)
{
    int c = 0;
    char h = 0;
    while(true)
    {
        write(wfd,&h,1);
        printf("child:%d\n",c++);
        sleep(10);
    }
}

void fathre(int rfd)
{
    char buffer[1024];
    while(true)
    {
        sleep(100);
        buffer[0]=0;
        ssize_t n = read(rfd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]=0;//清空数组
            cout<<buffer<<endl;
        }
        else if(n == 0)
        {
            cout<<"进程退出："<<n<<endl;
            sleep(5);
            break;
        }
        else
        {
            break;
        }
    } 
}

int main()
{
    int fds[2]={0};
    int n = pipe(fds);
    if(n < 0)
    {
        cout<<"pipe error"<<endl;
    }
    cout<<"fds[0]:"<<fds[0]<<endl;
    cout<<"fds[1]:"<<fds[1]<<endl;
    pid_t pid = fork();
    if(pid == 0)//子进程
    {
        close(fds[0]);
        childw(fds[1]);
        close(fds[1]);
        exit(0);
    }
    //父进程
    close(fds[1]);
    fathre(fds[0]);
    close(fds[0]);

    sleep(5);

    int status = 0;
    int ret = waitpid(pid,&status,0);
    if(ret > 0)
    {
        printf("exit code: %d, exit signal: %d\n", (status>>8)&0xFF, status&0x7F);
        sleep(5);
    }
    return 0;
}
